<template>
	<view class="app-touch-container"
        @touchmove="touchmove"
        @touchstart="touchstart"
        @touchend="touchend">
    <slot></slot>
  </view>
</template>

<script lang="ts" setup>
import { ref, defineProps, defineEmits } from 'vue'

const props = defineProps({
  singleDirection: {
    type: Boolean,
    default: true,
    descriptors: '是否单方向,要么X轴,要么Y轴'
  }
});

const emit = defineEmits<{
  moveStart: []
  move: [e: { moveX: number; moveY: number }]
  moveEnd: [e: { moveX: number; moveY: number }]
}>()

//0未开始 1开始计算 2X轴 3Y轴
const directionStatus = ref(0)

const startPosition = ref({ x: 0, y: 0 })
const moveDistance = ref({ x: 0, y: 0 })
const touchstart = (e)=>{
  const touche = e.touches[0] || {}
  startPosition.value = {
    x: touche.clientX || 0,
    y: touche.clientY || 0
  }
  moveDistance.value = {
    moveX: 0,
    velocityX: 0,
    accelerationX: 0,

    moveY: 0,
    velocityY: 0,
    accelerationY: 0
  }
  directionStatus.value = 1
  emit('moveStart')
}

const touchmove = (e)=>{
  e.preventDefault();

  const touche = e.touches[0] || {}
  const currentPositionX = touche.clientX || 0
  const currentPositionY = touche.clientY || 0

  const { x, y } = startPosition.value

  const move  = {
    moveX: currentPositionX - x,
    moveY: currentPositionY - y,
  }

  if(Math.abs(move.moveX) > Math.abs(move.moveY)){
    //X轴
    if(directionStatus.value === 1){
      directionStatus.value = 2
    }
  }else {
    //Y轴
    if(directionStatus.value === 1){
      directionStatus.value = 3
    }
  }
  if(props.singleDirection && directionStatus.value === 2){
    move.moveY = 0
  }else if(props.singleDirection && directionStatus.value === 3){
    move.moveX = 0
  }
  moveDistance.value = move
  emit('move', move)
}
const touchend = ()=>{
  directionStatus.value = 0
  emit('moveEnd', moveDistance.value)
}
</script>

<style lang="scss">
	.app-touch-container{
    width: inherit;
    height: inherit;
  }
</style>
